<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="true">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="备品单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="spareOrderId">
              <a-input type="list" v-model="model.spareOrderId" disabled placeholder="单号自动生成" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceId">
              <j-dict-select-tag type="list" v-model="model.deviceId" dictCode="ene_device,device_name,device_id" placeholder="请输入设备名称" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="备品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sparepartId">
              <j-dict-select-tag type="list" v-model="model.sparepartId" dictCode=" ene_spare_parts,name, id" placeholder="请输入备品名称" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发起人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="initiatorId">
              <j-dict-select-tag type="list" v-model="model.initiatorId" dictCode=" sys_user,realname, id" placeholder="审批后自动生成" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="来源标志" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sourceMark">
              <!--              <a-input v-model="model.sourceMark" placeholder="请输入来源标志"  ></a-input>-->
              <j-dict-select-tag
                type="list"
                v-model="model.sourceMark"
                dictCode="department_source"
                placeholder="请选择在线状态"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发起时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subtime">
              <j-date placeholder="请选择发起时间"  v-model="model.subtime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalId">
              <j-dict-select-tag type="list" v-model="model.approvalId" dictCode=" sys_user,realname,id" placeholder="审批后自动生成" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
<!--              <a-input v-model="model.status"  placeholder="请输入审批状态"  ></a-input>-->
              <j-dict-select-tag
                type="list"
                v-model="model.status"
                dictCode="approval_status"
                placeholder="请选择在线状态"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalTime">
              <j-date placeholder="审批后自动生成"  v-model="model.approvalTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>

<!--          <a-col :span="12">
            <a-form-model-item label="审批意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalInfo">
              <a-input v-model="model.approvalInfo" placeholder="请输入审批意见"  ></a-input>
            </a-form-model-item>
          </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-divider  orientation="left" style="margin-left: 0; padding-left: 0;">备品领用</a-divider>
    <j-form-container :disabled="formDisabled" >
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="领用人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="takeBy">
              <j-dict-select-tag type="list" v-model="model.takeBy" dictCode=" sys_user,realname,username" placeholder="选择领用人" :allowSearch="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="领用数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receviedNum">
              <a-input v-model="model.receviedNum" placeholder="请输入领用数量"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="领用时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="takeTime">
              <j-date placeholder="自动生成" disabled v-model="model.takeTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="剩余数量" :labelCol="labelCol" :wrapperCol="wrapperCol"  prop="remainingNum">
              <a-input v-model="model.remainingNum" disabled="true"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="备品领用记录" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="spareReceivedTable.loading"
          :columns="spareReceivedTable.columns"
          :dataSource="spareReceivedTable.dataSource"
          :maxHeight="300"
          :disabled="true"
          :rowNumber="true"
          :rowSelection="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
export default {
  name: 'EnedeviceSparepartApprovalForm',
  mixins: [JEditableTableModelMixin],
  components: {
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      model:{
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        deviceId: [
          { required: true, message: '请输入设备id!'},
        ],
      },
      activeKey: 'spareReceived',
      tableKeys:['spareReceived', ],
      refKeys: ['spareReceived', ],
      spareReceivedTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '领用人',
            key: 'receviedBy',
            type: FormTypes.sel_search,
            dictCode:"sys_user,realname,username",
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '申请数量',
            key: 'number',
            type: FormTypes.input,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '领用时间',
            key: 'receviedTime',
            type: FormTypes.date,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
        ]
      },
      url: {
        add: "/device/enedeviceSparepartApproval/add",
        edit: "/device/enedeviceSparepartApproval/edit",
        queryById: "/device/enedeviceSparepartApproval/queryById",
        spareReceived: {
          list: '/device/enedeviceSparepartApproval/querySpareReceivedByMainId'
        },
      }
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    console.log('Model ID:', this.model.id);
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    logModel() {
      console.log('Model:', this.model);
    },
    addBefore(){
      this.spareReceivedTable.dataSource=[]
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      console.log('editAfter')
      this.logModel()
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.spareReceived.list, params, this.spareReceivedTable)
      }
    },
    validateSubForm(allValues){
      return new Promise((resolve,reject)=>{
        Promise.all([
        ]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        spareReceivedList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg){
      this.$message.error(msg)
    },
    submitForm () {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log("111111",this.model.receviedNum)
          console.log("222222221",typeof (this.model.remainingNum))
          console.log("ccccccccccccccc",this.model.receviedNum > this.model.remainingNum,typeof(this.model.receviedNum))
          let receviedNum = parseInt(this.model.receviedNum)
          let remainingNum = parseInt(this.model.remainingNum)
          let flag =receviedNum >remainingNum
          console.log("flag",flag)
          if (flag) {
            this.$message.error('领用数量不能超过剩余数量');
            return; // 阻止表单提交
          }
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'put';
          }
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
  }
}
</script>